package com.sangmo.fts.process.storage.service;

import com.sangmo.boot.framework.common.utils.DateUtils;
import com.sangmo.boot.framework.data.idm.IdentityManager;
import com.sangmo.boot.framework.plugin.dataview.crud.service.BaseViewService;
import com.sangmo.boot.framework.plugin.dataview.data.IDataViewRepo;
import com.sangmo.fts.basic.service.FileUploadService;
import com.sangmo.fts.common.authority.service.AuthorityEntityService;
import com.sangmo.fts.process.storage.interfaces.CsfAgreementCreation;
import com.sangmo.fts.process.storage.model.CsfAgreement;
import com.sangmo.fts.process.storage.model.CsfContract;
import com.sangmo.fts.process.storage.repo.CsfAgreementRepo;
import com.sangmo.fts.process.storage.service.CsfContractService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@Transactional
public class CsfAgreementEntityService extends AuthorityEntityService<CsfAgreement> {

    @Autowired
    private CsfAgreementRepo csfAgreementRepo;

    @Autowired
    private IdentityManager identityManager;

    @Autowired
    private CsfContractService csfContractService;

    @Autowired
    private FileUploadService fileUploadService;

    @Override
    protected IDataViewRepo<CsfAgreement> getRepo() {
        return csfAgreementRepo;
    }

    @Override
    protected void onCreate(CsfAgreement entity, Object bo) {
        super.onCreate(entity, bo);
        entity.setCode(DateUtils.format(new Date(), "yyyyMMddHHmm") + identityManager.next("CSF_AGREEMENT", 4));
        CsfAgreementCreation creation = (CsfAgreementCreation) bo;
        CsfContract contract = csfContractService.get(creation.getContractId());
        entity.setBuyerId(contract.getBuyerId());
        entity.setSellerId(contract.getSellerId());
    }

    @Override
    protected void afterCreated(CsfAgreement entity, Object bo) {
        super.afterCreated(entity, bo);
        CsfAgreementCreation creation = (CsfAgreementCreation) bo;
        if (null != creation.getSellerConfirmDoc()) {
            fileUploadService.updateRef(creation.getSellerConfirmDoc(), ""+entity.getId(), "CsfAgreement.Seller");
        }
    }

    protected void buyerConfirm(CsfAgreement entity) {
        entity.setBuyerConfirm(true);
        this.save(entity);
    }

    protected void sellerConfirm(CsfAgreement entity) {
        entity.setSellerConfirm(true);
        this.save(entity);
    }

    protected void bankConfirm(CsfAgreement entity) {
        entity.setBankConfirm(true);
        this.save(entity);
    }

    protected void storageConfirm(CsfAgreement entity) {
        entity.setStorageConfirm(true);
        this.save(entity);
    }

    protected CsfAgreement findByContractId(Long contractId) {
        return csfAgreementRepo.findByContractId(contractId);
    }
}
